package com.huazhu.ticket.train.common;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Http请求工具类
 *
 * @author gaoyi
 */
public class HttpHelper {


    /**
     * 发送POST请求，并反序列化结果字符串为对象
     *
     * @param url
     * @param body
     * @param contentType
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T httpPost(String url, String body, String contentType, Class<T> tClass) {
        if (contentType == null || contentType.isEmpty()) {
            contentType = "application/json; charset=UTF-8";
        }
        String respBody = doHttpRequest(url, HttpMethod.POST, body, contentType, null);
        T t = JsonUtil.toObject(respBody, tClass);
        return t;
    }

    /**
     * 发送POST请求，可以设置header
     *
     * @param url
     * @param body
     * @param contentType
     * @param headerMap
     * @return
     */
    public static String httpPostWithHeaders(String url, String body, String contentType,
                                             Map<String, String> headerMap) {
        if (contentType == null || contentType.isEmpty()) {
            contentType = "application/json";
        }
        return doHttpRequest(url, HttpMethod.POST, body, contentType, headerMap);
    }

    /**
     * 请求核心方法
     *
     * @param url
     * @param method
     * @param body
     * @param contentType
     * @param headerMap
     * @return
     */
    private static String doHttpRequest(String url, HttpMethod method, String body, String contentType,
                                        Map<String, String> headerMap) {
        RestTemplate restTemplate = new RestTemplate();
        MediaType mediaType;
        if (contentType == null || contentType.isEmpty()) {
            mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        } else {
            mediaType = MediaType.parseMediaType(contentType + "; charset=UTF-8");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        if (headerMap != null) {
            for (String key : headerMap.keySet()) {
                headers.add(key, headerMap.get(key));
            }
        }
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        return restTemplate.exchange(url, method, entity, String.class).getBody();
    }

}
